package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.LoginVo;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        String name = dto.getName();
        String password = dto.getPassword();
        Map<String, Object> resultMap = new HashMap<>();
        if (name.isEmpty() && password.isEmpty()){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 查询数据库
        WmUser user = lambdaQuery().eq(WmUser::getName, name).one();
        if (Objects.isNull(user)){
            throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 检查账号状态
        if (user.getStatus()==1){
            throw new CustomException(AppHttpCodeEnum.INVALID_STATUS);
        }
        // 校验密码
        if(!BCrypt.checkpw(password,user.getPassword())){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        user.setPassword("");
        resultMap.put("user",user);
        resultMap.put("token",token);

        return ResponseResult.okResult(resultMap);
    }
}